using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DM.Entity;
using webapp4U;

namespace DM.DAO
{
    public enum Root
    {
        San_Pham = 17,
        Quan_He_Co_Dong = 19,
        Tin_Tuc = 20,
        Doi_Tac = 21,
        Tuyen_Dung = 24
    }
    public enum RootUnique
    {
        Gioi_Thieu = 6,
        Lien_He = 23,
        Cam_Ket = 22,
    }

    
    public class Common
    {
        public static Int32 TiengViet = 1;
        public static Int32 TiengAnh = 2;
        //Các loại tin bắt đầu bằng tiền tố :LoaiTin
        //Các loại tin tiếng việt 
        public static Int32 LoaiTinGioiThieu = 6;
        public static Int32 LoaiTinSanPham = 17;
        public static Int32 LoaiTinQuanHeCoDong = 19;
        public static Int32 LoaiTinTinTuc = 20;
        public static Int32 LoaiTinDoiTac = 21;
        public static Int32 LoaiTinCamKet = 22;
        public static Int32 LoaiTinLienHe= 23;
        public static Int32 LoaiTinTuyenDung = 24;
        //Các tin chi tiết bắt đầu bằng tiền tố : Tin
        //Các tin chi tiết tiếng việt
        public static Int32  TinGioiThieuChung= 25;
        public static Int32  TinTamNhin=26 ;
        public static Int32  TinVanHoaDoanhNghiep=27 ;
        public static Int32  TinCongNgheThietBi=28 ;
        public static Int32  TinMicromalting=29 ;
        public static Int32  TinHinhAnhCongTy=30 ;
        public static Int32  TinGioiThieuSanPHam=32 ;
        public static Int32  TinDieuLeCongTy=33 ;
        public static Int32  TinThongTinTuHDQT=34 ;
        public static Int32  TinNghiQuyetTuHDQT=35 ;
        public static Int32  TinBaoCaoThuongNien=36 ;
        public static Int32  TinBaoCaoQuy=37 ;
        public static Int32  TinBaoCaoNam=38 ;
        public static Int32  TinThongTinThiTruong=41 ;
        public static Int32  TinThongTinSanPham= 42;
        public static Int32  TinThongTinKhachHang= 43;
        public static Int32  TinKhachHang= 44;
        public static Int32  TinNhaCungCap= 45;
        public static Int32  TinAnToanLuongThuc= 46;
        public static Int32  TinAnToanLaoDong= 47;
        public static Int32  TinDamBaoMoiTruong= 48;
        public static Int32  TinTuThienXaHoi= 49;
        public static Int32  TinThongTinLienHe= 50;
        public static Int32  TinThongTinTuyenDung= 51;

        public static String DefaultImg = "Photos/default.jpg";

        public static ArrayList DS2List(DataSet ds)
        {
            ArrayList list = new ArrayList();

            return list;
        }
        

        public static string HashMD5(string input)
        {
            MD5 md5 = MD5.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }
        public static string PhysicalApplicationPath()
        {
            return HttpContext.Current.Request.PhysicalApplicationPath;
        }
        public static int ParseInt32(string i)
        {
            try
            {
                return Int32.Parse(i);
            }
            catch (Exception)
            {
                return -1;
            }
        }
        public static DateTime ParseDateTime(string date)
        {
            try
            {
                return DateTime.Parse(date);
            }
            catch (Exception)
            {
                return DateTime.Now;
            }
        }
        public static void Show(string sMessage)
        {
            HttpContext.Current.Response.Write("<script language='javascript'>window.alert('" + sMessage +
                                               "');</script>");
        }

        public static void Show(string sMessage, string url)
        {
            HttpContext.Current.Response.Write("<script language='javascript'>window.alert('" + sMessage +
                                               "');window.location.href='" + url + "';</script>");
        }

        /// <summary>
        /// Convert từ ListItem tới DataTable
        /// </summary>
        /// <typeparam name="T">Loại Entity</typeparam>
        /// <param name="list">list các thể hiện của Entity</param>
        /// <returns>Trả lại DataTable</returns>

        public static DataTable ConvertGList2DataTable<T>(List<T> list)
        {
            //Create table structure
            DataTable dataTable = CreateStructDataTable<T>();
            Type endType = typeof (T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(endType);
            //Get the ListItem and add the list)
            foreach (T item in list)
            {
                DataRow row = dataTable.NewRow();
                foreach (PropertyDescriptor entry in properties)
                {
                    row[entry.Name] = entry.GetValue(item);
                }
                dataTable.Rows.Add(row);
            }
            return dataTable;
        }
        /// <summary>
        /// Tạo cấu trúc DataTable của 1 loại Entity T
        /// </summary>
        /// <typeparam name="T">Loại Entity</typeparam>
        /// <returns>DataTable</returns>
        private static DataTable CreateStructDataTable<T>()
        {
            Type endType = typeof (T);
            //Đặt tên bảng
            DataTable table = new DataTable(endType.Name);
            //Tạo các property cho table
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(endType);
            foreach (PropertyDescriptor property in properties)
            {
                //add property as column
                table.Columns.Add(property.Name, property.PropertyType);
            }
            return table;
        }
        public static string ApplicationPath
        {
            get
            {
                string url = HttpContext.Current.Request.ApplicationPath;
                if (url.EndsWith("/"))
                    return url;
                return url + "/";
            }
        }
        /// <summary>
        /// UpLoad anh dai dien tintuc
        /// </summary>
        /// <param name="fUpload">FileUpload control id</param>
        /// <param name="path">Duong Dan</param>
        /// <returns></returns>
        public static string FilePhoto_Upload(FileUpload fUpload, string path)
        {
            string strFileName = "";
            // kiem tra xem user co chon hinh dai dien ko
            if (fUpload.HasFile)
            {
                // kiem tra phan mo rong cua file co hop le hay khong
                string strExtension = Path.GetExtension(fUpload.FileName).ToUpper();
                if (strExtension == ".JPG" || strExtension == ".GIF" || strExtension == ".JPEG" ||
                    strExtension == ".PNG")
                {
                    // lay ten file de khong bi trung file + phan mo rong cua file can upload
                    strFileName = webapp4U.Common.GetFileName() + Path.GetExtension(fUpload.FileName);

                    //duong dan tao save file Large
                    string strFilePathLarge = path + strFileName;


                    //thuc hien save file Large len server
                    EnumUpload uploadLarge = FileProcess.UpLoadImage(fUpload, strFilePathLarge, 200);
                    strFileName = "Photos/" + strFileName;
                }
            }
            else
            {
                strFileName = DefaultImg;
            }
            return strFileName;
        }
        /// <summary>
        /// Xoa file tren server
        /// </summary>
        /// <param name="filePath">Duong dan tu Root den file</param>
        public static void deleteFile(string filePath)
        {
            try
            {
                FileInfo TheFile = new FileInfo(PhysicalApplicationPath() + filePath);
                if (TheFile.Exists)
                    TheFile.Delete();
            }
            catch (Exception ex)
            {
                Show(ex.ToString());
            }
        }
        public static String FilterStringForColumn(String chuoi,int num)
        {
            if(chuoi.Trim().Length<num)
            {
                return chuoi;
            }
            return chuoi.Substring(0, num).Trim() + " ...";
        }

        /// <summary>
        /// Upload file dùng trong upload phan bao cao
        /// </summary>
        /// <param name="fu">asp control FileUpload</param>
        /// <param name="path">tra ve duong dan cua file vua up len tren sever</param>
        /// <returns></returns>
        public static string UploadFile(FileUpload fu, string path)
        {
            string strFileName = "";

            if(fu.HasFile)
            {
                // kiem tra phan mo rong cua file co hop le hay khong
                string strExtension = Path.GetExtension(fu.FileName).ToUpper();
                // lay ten file de khong bi trung file + phan mo rong cua file can upload
                strFileName = Path.GetFileNameWithoutExtension(fu.FileName)+webapp4U.Common.GetFileName() + Path.GetExtension(fu.FileName);
                //duong dan tao save file Large
                string strFilePathLarge = path + strFileName;
                //thuc hien save file Large len server
                EnumUpload uploadLarge = FileProcess.UpLoadFile(fu, strFilePathLarge);
                strFileName = "Files/" + strFileName;
            }

            return strFileName;
        }


        /// <summary>
        /// Upload file dùng trong upload ảnh trong phần Slider
        /// </summary>
        /// <param name="fu">asp control FileUpload</param>
        /// <param name="path">tra ve duong dan cua file vua up len tren sever</param>
        /// <returns></returns>
        public static string UploadAnhSlide(FileUpload fu, string path)
        {
            string strFileName = "";

            if (fu.HasFile)
            {
                // kiem tra phan mo rong cua file co hop le hay khong
                string strExtension = Path.GetExtension(fu.FileName).ToUpper();
                if (strExtension == ".JPG" || strExtension == ".GIF" || strExtension == ".JPEG" ||
                    strExtension == ".PNG")
                {
                    // lay ten file de khong bi trung file + phan mo rong cua file can upload
                    strFileName = webapp4U.Common.GetFileName() + Path.GetExtension(fu.FileName);

                    //duong dan tao save file Large
                    string strFilePathLarge = path + strFileName;

                    //thuc hien save file Large len server
                    EnumUpload uploadLarge = FileProcess.UpLoadFile(fu, strFilePathLarge);
                    strFileName = "Photos/Slide/" + strFileName;
                }
            }
            return strFileName;
        }

        public static void UploadQuangCao(FileUpload fileUpload, string fileName, string fileType)
        {
            string url = HttpContext.Current.Request.UrlReferrer.ToString();
            if (fileUpload.HasFile)
            {
                string ext =
                    fileUpload.PostedFile.FileName.Substring(fileUpload.PostedFile.FileName.LastIndexOf(".") + 1);
                try
                {
                    if (ext.ToUpper() == fileType.ToUpper())
                    {
                        if (fileUpload.PostedFile.ContentLength < 1024000)
                        {
                            fileUpload.SaveAs(System.Web.Hosting.HostingEnvironment.MapPath("~/") + fileName);
                        }
                        else
                        {
                            Show("Up anh loi", url);
                        }
                    }
                    else
                    {
                        Show("Up anh loi", url);
                    }
                }
                catch (Exception ex)
                {
                    Show(ex.ToString(), url);
                }
                FileInfo xmlFile = new FileInfo(System.Web.Hosting.HostingEnvironment.MapPath("~/") + "Photos/QuangCao/catalogimage.xml");
                if (xmlFile.Exists)
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(System.Web.Hosting.HostingEnvironment.MapPath("~/") + "Photos/QuangCao/catalogimage.xml");
                    XmlNode catalogNote = xmlDocument.DocumentElement;
                    XmlNode imageNode = xmlDocument.CreateElement("image");
                    catalogNote.AppendChild(imageNode);
                    XmlNode imageUrlNote = xmlDocument.CreateElement("urlImage");
                    XmlNode Link = xmlDocument.CreateElement("Link");
                    XmlNode Name = xmlDocument.CreateElement("Name");
                    imageNode.AppendChild(imageUrlNote);
                    imageNode.AppendChild(Link);
                    imageNode.AppendChild(Name);
                    imageUrlNote.AppendChild(xmlDocument.CreateTextNode("../../" + fileName));
                    Link.AppendChild(xmlDocument.CreateTextNode("#"));
                    Name.AppendChild(xmlDocument.CreateTextNode(fileName.Substring(fileName.LastIndexOf(".") - 1, 1)));
                    xmlDocument.Save(System.Web.Hosting.HostingEnvironment.MapPath("~/") + "Photos/QuangCao/catalogimage.xml");
                }
                else
                {
                    XmlDocument doc = new XmlDocument();
                    XmlNode docNode = doc.CreateXmlDeclaration("1.0", "utf-8", null);

                    XmlNode catalogNode = doc.CreateElement("catalog");
                    XmlNode imageNode = doc.CreateElement("image");
                    XmlNode urlNode = doc.CreateElement("urlImage");
                    XmlNode LinkNode = doc.CreateElement("Link");
                    XmlNode NameNode = doc.CreateElement("Name");
                    urlNode.AppendChild(doc.CreateTextNode("../../Photos/QuangCao/1." + fileType));
                    LinkNode.AppendChild(doc.CreateTextNode("#"));
                    NameNode.AppendChild(doc.CreateTextNode("1"));
                    imageNode.AppendChild(LinkNode);
                    imageNode.AppendChild(urlNode);
                    imageNode.AppendChild(NameNode);
                    catalogNode.AppendChild(imageNode);
                    doc.AppendChild(docNode);
                    doc.AppendChild(catalogNode);
                    doc.Save(System.Web.Hosting.HostingEnvironment.MapPath("~/") + "Photos/QuangCao/catalogimage.xml");
                }
            }
        }
    }
}
